import {useState} from "react";
import {LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import {Flex, GetProp, message, Upload, UploadProps} from "antd";
import {AuthorizationKey} from "@/app/lib/HttpProtocol";
import {getToken} from "@/app/lib/security";


type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: FileType) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

// @ts-ignore
export default function IconUpload({onUploadSuccess,initUrl}:{onUploadSuccess:any,initUrl?:string}){
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string|undefined>(initUrl);

  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as FileType, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
      let response = info.file.response;
      if(response.code == 200){
        onUploadSuccess(response.data)
      }else{
        message.error(response.msg)
      }
    }
  };

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );

  const getExtraData: UploadProps['data'] = (file) => ({
    policy: "Private",
  });

  return (
    <Upload
      name="file"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action={process.env.NEXT_PUBLIC_BASE_URL+"/file/upload"}
      data={getExtraData}
      // @ts-ignore
      headers={{sessionid:getToken()}}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%',height:'100%'}} /> : uploadButton}
    </Upload>
  );

}